package cn.lg.soar.redis.serializer;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.StandardCharsets;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class RedisKeySerializer implements RedisSerializer<String> {

    private final String prefix;

    public RedisKeySerializer(String prefix) {
        this.prefix = prefix + ":";
    }

    @Override
    public byte[] serialize(String string) throws SerializationException {
        if (string == null) {
            throw new RuntimeException("redis key cannot null");
        }
        return (this.prefix + string).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public String deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null) {
            return null;
        }
        return new String(bytes, StandardCharsets.UTF_8).replaceFirst(this.prefix, "");
    }
}
